package com.example.appinstalldemo.utils;

import android.content.Context;
import android.os.Environment;

import com.tencent.mmkv.MMKV;

/**
 * @author: njb
 * @date: 2023/8/8 0:08
 * @desc:
 */
public class MMKVUtils {
    private MMKV mmkv;
    private static volatile MMKVUtils mInstance;

    private MMKVUtils() {

    }

    public void init(Context context) {
        //mmkv初始化
        MMKV.initialize(context, Environment.getExternalStorageDirectory().getAbsolutePath() + "/mmkv");
        mmkv = MMKV.mmkvWithID("MyId", MMKV.MULTI_PROCESS_MODE);
        //是否开启跨进程
        mmkv.encode("bool", true);
    }

    public static MMKVUtils getInstance() {
        if (null == mInstance) {
            synchronized (MMKVUtils.class) {
                if (null == mInstance) {
                    mInstance = new MMKVUtils();
                }
            }
        }
        return mInstance;
    }

    public void encode(String key, Object value) {
        if (value instanceof String) {
            mmkv.encode(key, (String) value);
        } else if (value instanceof Integer) {
            mmkv.encode(key, (Integer) value);
        } else if (value instanceof Boolean) {
            mmkv.encode(key, (Boolean) value);
        } else if (value instanceof Long) {
            mmkv.encode(key, (Long) value);
        } else if (value instanceof Float) {
            mmkv.encode(key, (Float) value);
        } else if (value instanceof Double) {
            mmkv.encode(key, (Double) value);
        }
    }

    public Integer decodeInt(String key) {
        return mmkv.decodeInt(key);
    }

    public String decodeString(String key) {
        return mmkv.decodeString(key, "");
    }

    public Boolean decodeBoolean(String key) {
        return mmkv.decodeBool(key);
    }

    public Long decodeLong(String key) {
        return mmkv.decodeLong(key);
    }

    public Float decodeFloat(String key) {
        return mmkv.decodeFloat(key);
    }

    public Double decodeDouble(String key) {
        return mmkv.decodeDouble(key);
    }
}
